var that = '';

Page({
  data: {
    img: '../../images/plant.jpg',
    imgB64: '',
    content: '',
    ishow: false,
    searchKey: '',
  },

  onLoad(options) {
    that = this;
    console.log(options);
    that.setData({
      img: options.img
    })
  },

  //选择图片
  chooseimgTap: function () {
    that.setData({
      ishow: false,
      content: ''
    });
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths[0];
        that.getB64ByUrl(tempFilePaths);
        that.setData({
          img: tempFilePaths
        });
      }
    })
  },
  //转b64
  getB64ByUrl: function (url) {
    const FileSystemManager = wx.getFileSystemManager();
    FileSystemManager.readFile({
      filePath: url,
      encoding: 'base64',
      success(res) {
        that.setData({
          imgB64: res.data
        });
      }
    })
  },
  //获取token
  getToken: function (callback) {
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=cxb09hxA168RMCdyxNFx7zZ8&client_secret=85Nca1YweSadYpekXRxGGmiT5Gi4Xj3T',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        var token = res.data.access_token;
        return callback(token);
      }
    });
  },
  // 通用物品识别
  generalTap: function (e) {
    const imgB64 = that.data.imgB64;
    if (!imgB64) {
      that.setData({
        ishow: true
      });
      return;
    };
    that.getToken(function (token) {
      that.getGeneralTapResult(token);
    });
  },
  getGeneralTapResult: function (token) {
    wx.request({
      url: 'https://aip.baidubce.com/rest/2.0/image-classify/v2/dish?access_token=' + token, //仅为示例，并非真实的接口地址
      method: "post",
      data: {
        image: that.data.imgB64,
        baike_num: 5
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        console.log(res);
        that.setData({
          content: res.data.result
        });
      }
    });
  },
  // 跳转页面
  goCamera: function () {
    wx.navigateTo({
      url: '/pages/camera/camera',
    })
  },
  goMore: function (e) {
    console.log(e);
    var title = e.currentTarget.dataset.title;
    var image = e.currentTarget.dataset.baike.image_url;
    var description = e.currentTarget.dataset.baike.description;
    wx.navigateTo({
      url: '/pages/demo/demo?title='+title+'&image='+ image +'&description='+description,
    })
  }
})